<?php

Class Application_Model_Mapper_Gb {

	protected $_dbTable = null;
	protected $_dbAdapter = null;

	public function  __construct() {

	}

	public function insert(Application_Model_Gb $gb) {
		$data = $gb->toArray();
		$this->getDbTable()->insert($data);
	}

	public function update(Application_Model_Gb $gb) {
		$data = $gb->toArray();
		$this->getDbTable()->update($data);
	}

	public function delete(Application_Model_Gb $gb) {
		$id = $gb->getId();
		$this->getDbTable()->delete($id);
		return $this;
	}

	public function save(Application_Model_Gb $gb) {
		if ($gb->getId()) {
			$this->update($gb);
		} else {
			$this->insert($gb);
		}
		return $this;
	}

	public function fetch($rate = null, $perpage = null) {

	}

	public function findById($id) {
		$result = $this->getDbTable()->find($id);

		if (0 == count($result)) return false;

		$gb = new Application_Model_Gb($row);
		$row = $result->current();

		return $this->toObject($row);
	}

	public function setDbTable($dbTable) {
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable() {
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Gb');
		}
		return $this->_dbTable;
	}

	public function getGbList($rate, $perpage) {
		//$gbDbTable = new Application_Model_DbTable_Gb();
		/*
		$stmt = $this->_dbAdapter->select()
			->from(array('g' => 'gb'), array('id', 'path', 'text', 'date'))
			->joinLeft(array('u' => 'users'), 'u.id = g.user', array('login'))
			->order('g.path')
			->limit($perpage, $rate * $perpage - $perpage);
		*/
		$sql = 'SELECT g.id, g.path, g.text, g.date, u.login, u.fio
			FROM gb AS g
			INNER JOIN users AS u ON u.id = g.user
			ORDER BY g.path ASC LIMIT ' . ($rate * $perpage - $perpage) . ', ' . $perpage;

		$stmt = $this->_dbAdapter->fetchAll($sql);
		return $stmt;
	}

	public function add($path, $text, $date) {
		$this->setPath($path)
			->setText($text)
			->setDate($date);
		return $this;
	}

}